<?php
require_once '../func/db.class.php';
require_once '../func/auth.php';
require_once '../func/utils.php';

session_start();
header('Content-Type: application/json');

if (!isAuthenticated()) {
    echo json_encode(['success' => false, 'message' => '未登录']);
    exit;
}

$db = new Db();
$userId = getCurrentUserId();

// 修改用户名
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = json_decode(file_get_contents("php://input"), true);
    if (isset($input['action']) && $input['action'] === 'update_username') {
        $newUsername = trim($input['username']);
        if (!$newUsername) {
            echo json_encode(['success' => false, 'message' => '用户名不能为空']);
            exit;
        }

        $exists = $db->query("SELECT id FROM users WHERE username = ? AND id != ?", [$newUsername, $userId]);
        if ($exists) {
            echo json_encode(['success' => false, 'message' => '用户名已存在']);
            exit;
        }

        $db->update('users', ['username' => $newUsername], ['id' => $userId]);
        $_SESSION['username'] = $newUsername;

        echo json_encode(['success' => true, 'message' => '用户名更新成功']);
        exit;
    }
}

// 获取用户信息
$user = $db->query("SELECT username, last_login_ip, last_login_time FROM users WHERE id = ?", [$userId])[0];
$history = $db->query("SELECT login_time, ip_address FROM login_history WHERE user_id = ? ORDER BY login_time DESC LIMIT 10", [$userId]);

echo json_encode([
    'success' => true,
    'user' => $user,
    'history' => $history
]);
